﻿using System;
using System.Web.Mvc;
using GabageFactory.Models;
using GabageFactory.Utiliy.Crypt;
using System.Text.RegularExpressions;
using System.Net.Mail;

namespace GabageFactory.Controllers
{
    [Authorize]
    public class UserController : BaseController
    {
        private UserReposity userReposity;

        private StackReposity factoryReposity;

        private RoleReposity roleReposity;

        public UserController()
        {
            userReposity = new UserReposity();
            factoryReposity = new StackReposity();
            roleReposity = new RoleReposity();
        }
        
        //
        // GET: /User/

        public ActionResult Index(string name, int? roleId, int? factoryId)
        {
            ActionResult result = AllowForRole(RoleEnum.Administrator);
            if (result != null)
            {
                return result;
            }
            
            int fId = factoryId.HasValue ? factoryId.Value : 0;
            int rId = roleId.HasValue ? roleId.Value : 0;
            ShowFactoryList(fId);
            ShowRoleList(rId);

            return View(userReposity.QueryUsers(name, rId, fId));
        }

        //
        // GET: /User/Details/5

        public ActionResult Details(int id)
        {
            ActionResult result = AllowForRole(RoleEnum.Administrator);
            if (result != null)
            {
                return result;
            }
            return View(userReposity.GetUserById(id));
        }

        //
        // GET: /User/Create
        public ActionResult Create()
        {
            ActionResult result = AllowForRole(RoleEnum.Administrator);
            if (result != null)
            {
                return result;
            }
            ShowFactoryAndRoleList(null);
            return View(new User());
        } 

        //
        // POST: /User/Create

        [HttpPost]
        public ActionResult Create(User user)
        {
            ActionResult result = AllowForRole(RoleEnum.Administrator);
            if (result != null)
            {
                return result;
            }
            try
            {
                validate(user, true);
                User existed = userReposity.GetUserByName(user.Name);
                if (existed != null)
                {
                    ModelState.AddModelError("Name", "该登录帐号已经被使用，请更改登录帐号重新创建.");
                    throw new Exception("Input form is invalid!");
                }
                user.NeedResetPwd = true;
                user.CreateTime = DateTime.Now;
                user.ModifyTime = DateTime.Now;
                string password = user.Password;
                user.Password = MD5.md5(user.Password);
                userReposity.CreateUser(user);
                userReposity.SendPwdEmail(user.Email, user.Name, password);

                return RedirectToAction("Index");
            }
            catch
            {
                user.Password = "";
                ShowFactoryAndRoleList(user);
                return View(user);
            }
        }
        
        //
        // GET: /User/Edit/5
 
        public ActionResult Edit(int id)
        {
            ActionResult result = AllowForRole(RoleEnum.Administrator);
            if (result != null)
            {
                return result;
            }
            User user = userReposity.GetUserById(id);
            ShowFactoryAndRoleList(user);
            return View(user);
        }

        //
        // POST: /User/Edit/5

        [HttpPost]
        public ActionResult Edit(User user)
        {
            ActionResult result = AllowForRole(RoleEnum.Administrator);
            if (result != null)
            {
                return result;
            }
            try
            {
                validate(user);
                
                User oldUser = userReposity.GetUserById(user.Id);
                oldUser.RealName = user.RealName;
                oldUser.Email = user.Email;
                oldUser.FactoryId = user.FactoryId;
                oldUser.Mobile = user.Mobile;
                oldUser.ModifyTime = DateTime.Now;
                oldUser.Phone = user.Phone;
                oldUser.RoleId = user.RoleId;                
                userReposity.EditUser(user);
 
                return RedirectToAction("Index");
            }
            catch
            {
                ShowFactoryAndRoleList(user);
                
                return View(user);
            }
        }

        //
        // GET: /User/ChangePwd/5

        public ActionResult ChangePwd(int id)
        {
            ActionResult result = AllowForRole(RoleEnum.Administrator);
            if (result != null)
            {
                return result;
            }
            User user = userReposity.GetUserById(id);
            ViewData["success"] = false;
            ViewData["PasswordLength"] = 6;
            ViewData["userName"] = user.Name;
            ChangePasswordModel model = new ChangePasswordModel();
            model.OldPassword = id.ToString();
            return View(model);
        }

        [HttpPost]
        public ActionResult ChangePwd(ChangePasswordModel model)
        {
            try {
                ViewData["success"] = false;
                ViewData["userName"] = "";
                ViewData["PasswordLength"] = 6;
                string userId = model.OldPassword;
                User user = userReposity.GetUserById(Int32.Parse(userId));
                if (user == null)
                {
                    ModelState.AddModelError("", "非法操作，该用户不存在.");
                }
                else
                {
                    ViewData["userName"] = user.Name;
                }
                if (ModelState.IsValid)
                {
                    
                    if (string.IsNullOrEmpty(model.NewPassword))
                    {
                        ModelState.AddModelError("NewPassword", "请填写新密码.");
                    }
                    if (string.IsNullOrEmpty(model.ConfirmPassword))
                    {
                        ModelState.AddModelError("ConfirmPassword", "请填写确认密码.");
                    }
                    if (model.NewPassword != model.ConfirmPassword)
                    {
                        ModelState.AddModelError("ConfirmPassword", "两次密码输入不正确，请重新填写.");
                    }

                    string password = model.NewPassword;
                    user.Password = MD5.md5(model.NewPassword);
                    user.NeedResetPwd = true;
                    user.ModifyTime = DateTime.Now;
                    userReposity.EditUser(user);
                    userReposity.SendPwdEmail(user.Email, user.Name, password);

                    ViewData["success"] = true;
                    ViewData["userName"] = user.Name;
                }
            }
            catch
            {
                ModelState.AddModelError("", "非法操作，该用户不存在.");
            }

            return View(model);
        }

        //
        // GET: /User/RequestChangePwd
        public ActionResult RequestChangePwd()
        {
            User user = (User)HttpContext.Session["currentUser"];
            ViewData["user"] = user;
            ViewData["success"] = false;

            return View();
        }

        [HttpPost]
        public ActionResult RequestChangePwd(FormCollection collection)
        {
            User user = (User)HttpContext.Session["currentUser"];
            Random r = new Random();

            string pwd = "";
            for (int i = 0; i < 6; i++)
            {
                pwd = pwd + r.Next(10);
            }
            User oldUser = userReposity.GetUserById(user.Id);
            oldUser.Password = MD5.md5(pwd);
            oldUser.NeedResetPwd = true;
            oldUser.ModifyTime = DateTime.Now;
            userReposity.EditUser(oldUser);
            userReposity.SendPwdEmail(oldUser.Email, oldUser.Name, pwd);

            ViewData["user"] = user;
            ViewData["success"] = true;

            return View();
        }

        //
        // GET: /User/Delete/5
        public ActionResult Delete(int id)
        {
            ActionResult result = AllowForRole(RoleEnum.Administrator);
            if (result != null)
            {
                return result;
            }
            User user = userReposity.GetUserById(id);
            ViewData["userName"] = user.Name;
            userReposity.DeleteUser(user);
            return View();
        }

        private void validate(User user, bool needValidPwd = false)
        {
            if(user.FactoryId <= 0 || user.FactoryId >= long.MaxValue)
            {
                ModelState.AddModelError("FactoryId", "用户所属堆场不能为空");
            }

            if (user.RoleId <= 0)
            {
                ModelState.AddModelError("RoleId", "用户角色不能为空");
            }
            
            if (string.IsNullOrEmpty(user.Name))
            {
                ModelState.AddModelError("Name", "登录帐号不能为空");
            }
            else if (user.Name.Length > 30)
            {
                ModelState.AddModelError("Name", "登录帐号不能超过30个字符");
            }

            if (string.IsNullOrEmpty(user.RealName))
            {
                ModelState.AddModelError("RealName", "用户名称不能为空");
            }
            else if (user.Name.Length > 30)
            {
                ModelState.AddModelError("RealName", "用户名称不能超过30个字符");
            }

            if (needValidPwd && string.IsNullOrEmpty(user.Password))
            {
                ModelState.AddModelError("Password", "密码不能为空");
            }

            if (needValidPwd && user.Password.Length < 6)
            {
                ModelState.AddModelError("Password", "密码不能少于6位");
            }

            if (string.IsNullOrEmpty(user.Email) || user.Email.Length > 30)
            {
                ModelState.AddModelError("Email", "电子邮箱不能为空，且长度不能大于30位");
            }
            else if (!Regex.IsMatch(user.Email, ".+@.+") )
            {
                ModelState.AddModelError("Email", "电子邮箱格式不正确");
            }

            if (!ModelState.IsValid)
            {
                throw new Exception("Input form is invalid!");
            }
        }
    }
}
